import 'dart:async';
import 'package:ball_lion/module/match_detail/live/live_loading.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/live/live_normal_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/get_icon.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';

class VerticalPanel extends StatefulWidget {
  const VerticalPanel({super.key, required this.logic});

  final LiveNormalLogic logic;

  @override
  State<VerticalPanel> createState() => _VerticalPanelState();
}

class _VerticalPanelState extends State<VerticalPanel> {
  Timer? countdown;
  DateTime? startTime;
  int? _countTime;
  bool notStart = false;
  bool _completion = false;
  final double barHeight = 72;

  late final QsPlayerLogic playerLogic;

  int? get countTime => _countTime;
  set countTime(int? value) => setState(() => _countTime = value);

  bool get completion => _completion;
  set completion(bool value) => setState(() => _completion = value);

  @override
  void initState() {
    playerLogic = Get.find<QsPlayerLogic>(tag: "${widget.logic.liveId}");
    startTime = DateTime.tryParse(widget.logic.liveDetail?.publishTime ?? "");
    if (startTime != null && widget.logic.waitStart) {
      countTime = startTime!.difference(DateTime.now()).inSeconds;
      countdown = Timer.periodic(const Duration(seconds: 1), (timer) {
        countTime = countTime! - 1;
        if (countTime == 0 || !widget.logic.waitStart) {
          timer.cancel();
        }
      });
    }
    super.initState();
  }

  void _playOrPause() {
    if (playerLogic.status == PlayStatus.started) {
      playerLogic.pause();
    } else if (playerLogic.status == PlayStatus.paused) {
      playerLogic.pauseToPlay();
    } else {
      playerLogic.doRefresh();
    }
  }

  String secondsToHHMMSS(int seconds) {
    String formatTwoDigits(int n) => n.toString().padLeft(2, '0');

    final int hours = seconds ~/ 3600;
    seconds %= 3600;
    final int minutes = seconds ~/ 60;
    final int remainingSeconds = seconds % 60;

    return '${formatTwoDigits(hours)}时${formatTwoDigits(minutes)}分${formatTwoDigits(remainingSeconds)}秒';
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<QsPlayerLogic>(
        tag: "${widget.logic.liveId}",
        builder: (player) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onHorizontalDragStart: (details) {
              if (playerLogic.duration != 0) {
                playerLogic.startSlide = true;
                playerLogic.onSlide = true;
                playerLogic.slidePosition =
                    playerLogic.currentPosition.toDouble();
              }
            },
            onHorizontalDragUpdate: (details) {
              if (playerLogic.duration != 0) {
                Logger().d(
                    "${details.delta.dx / Get.width * 60000} 当前时长：${playerLogic.formTime()} 总时长：${playerLogic.totalTime}");
                playerLogic.slidePosition +=
                    details.delta.dx / Get.width * 60000;
              }
            },
            onHorizontalDragEnd: (details) {
              if (widget.logic.liveDetail?.status == 2) {
                playerLogic.setPosition();
              }
            },
            child: Stack(
              alignment: Alignment.center,
              children: [
                if (countTime != null &&
                    countTime == 0 &&
                    !widget.logic.waitStart)
                  const QsText("主播正在赶来", color: Colours.white)
                else if (countTime != null && widget.logic.waitStart)
                  QsText(
                    "距离${startTime?.formatedString("MM月dd日HH:mm")}直播开始还有\n"
                    "${secondsToHHMMSS(countTime!)}",
                    color: Colours.white,
                    textAlign: TextAlign.center,
                  )
                else if (playerLogic.status == PlayStatus.completion)
                  Container(
                      alignment: Alignment.center,
                      color: Colours.black,
                      child: const QsText("直播已结束", color: Colours.white))
                else if (playerLogic.status == PlayStatus.idle ||
                    playerLogic.status == PlayStatus.prepared ||
                    playerLogic.status == PlayStatus.initialized) ...[
                  const Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      LiveLoading(
                        color: Colours.white,
                        size: 44,
                      ),
                      QsText("加载中", color: Colours.white)
                    ],
                  )
                ] else if (playerLogic.status == PlayStatus.error) ...[
                  Container(
                    alignment: Alignment.center,
                    color: Colours.black,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Expanded(child: Container()),
                        const QsText("视频加载失败，请稍后重试", color: Colours.white),
                        Container(height: 8),
                        QsButton(
                            onPressed: playerLogic.doRefresh,
                            text: "重新连接",
                            width: 74,
                            height: 30,
                            borderRadius: 6,
                            foregroundColor: Colours.main,
                            borderSide: const BorderSide(
                                color: Colours.main, width: 0.5)),
                        Expanded(
                            child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            if (playerLogic.errorCode.hasValue)
                              QsText("[${playerLogic.errorCode}]",
                                  fontSize: 12,
                                  color: Colors.white.withOpacity(0.5)),
                            Container(height: 8)
                          ],
                        ))
                      ],
                    ),
                  )
                ] else if (playerLogic.status == PlayStatus.completion) ...[
                  const QsText("直播已结束", color: Colours.white)
                ] else if (playerLogic.status == PlayStatus.stopped) ...[
                  const QsText("主播暂时离开，马上回来", color: Colours.white)
                ],
                if (playerLogic.startSlide)
                  Positioned.fill(
                    child: Container(
                        color: Colours.black.withOpacity(0.8),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                QsText(
                                  playerLogic.formTime(),
                                  fontSize: 20,
                                  color: Colours.main,
                                  needCenter: true,
                                ),
                                Container(width: 4),
                                QsText(
                                  "/${playerLogic.totalTime}",
                                  color: Colours.white,
                                  needCenter: true,
                                ).paddingOnly(top: 5)
                              ],
                            ),
                            SizedBox(
                              width: 160,
                              child: LinearProgressIndicator(
                                minHeight: 2,
                                value: playerLogic.slidePosition /
                                    playerLogic.duration,
                                valueColor: const AlwaysStoppedAnimation<Color>(
                                    Colours.main),
                                backgroundColor: Colours.white.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(13.5),
                              ),
                            )
                          ],
                        )),
                  ),
                Column(
                  children: [
                    const Spacer(),
                    if (playerLogic.duration != 0) _buildBottomBar(context)
                  ],
                )
              ],
            ),
          );
        });
  }

  Widget _buildBottomBar(BuildContext context) {
    return Container(
      height: barHeight,
      padding: EdgeInsets.only(
          bottom:
              MediaQuery.of(Get.context!).orientation == Orientation.landscape
                  ? 10
                  : Get.mediaQuery.padding.bottom),
      decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: [Colours.black.withOpacity(0.8), Colors.transparent],
              begin: Alignment.bottomCenter,
              end: Alignment.topCenter)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: <Widget>[
                IconButton(
                    onPressed: _playOrPause,
                    icon: Icon(
                      playerLogic.status == PlayStatus.paused
                          ? GetIcon.pause
                          : GetIcon.play,
                      color: Colours.white,
                      size: 24,
                    )),
                QsText(
                    playerLogic.startSlide
                        ? playerLogic.formTime()
                        : playerLogic.positionTime,
                    fontSize: 12,
                    color: Colours.white),
                Container(width: 4),
                Expanded(child: slider()),
                Container(width: 4),
                QsText(playerLogic.totalTime,
                    fontSize: 12, color: Colours.white),
                Container(width: 16)
              ],
            ),
          ),
          Container(height: 10)
        ],
      ),
    );
  }

  Widget slider() {
    return SliderTheme(
      data: SliderTheme.of(context).copyWith(
        trackHeight: 2,
        trackShape: const RoundedRectSliderTrackShape(),
        activeTrackColor: Colours.main,
        inactiveTrackColor: Colours.white.withOpacity(0.25),
        thumbColor: Colours.white,
        thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
        overlayShape: const RoundSliderOverlayShape(overlayRadius: 6),
        overlayColor: Colours.white.withOpacity(0.5),
      ),
      child: Slider(
        value: playerLogic.startSlide
            ? playerLogic.slidePosition
            : playerLogic.currentPosition.toDouble(),
        max: playerLogic.duration.toDouble(),
        allowedInteraction: SliderInteraction.tapAndSlide,
        onChangeStart: (value) {
          playerLogic.startSlide = true;
          playerLogic.onSlide = true;
          playerLogic.slidePosition = value;
        },
        onChanged: (value) => playerLogic.slidePosition = value,
        onChangeEnd: (value) => playerLogic.setPosition(),
      ),
    );
  }
}
